/**
 * 文章目录
 */

import Pubsub from '../../helper/Pubsub.js';
import State from '../../helper/State.js';

class SidebarDirectory {
  constructor($wrapper) {
    const _this = this;

    _this.$wrapper = $wrapper;

    _this.tplHead =
`<div class="head">
  <label class="mdui-text-color-theme-secondary">目录</label>
</div>`;

    let tplEmpty =
`<div class="empty item">
  <div class="mdui-valign" style="height: 100%;">
    <div class="content">
      <i class="mdui-icon material-icons mdui-text-color-theme-disabled mdui-m-b-2">featured_play_list</i>
      <div class="mdui-text-color-theme-secondary">没有文章目录</div>
    </div>
  </div>
</div>`;

    _this.$wrapper.html(_this.tplHead + tplEmpty);

    /**
     * 监听文章渲染完成事件
     */
    Pubsub.subscribe('article-rendered', (fileSha1) => {
      let $directory = _this.$wrapper.find('#directory-' + fileSha1);

      if (!$directory.length) {
        _this.$wrapper.append(`<div class="item" id="directory-${fileSha1}"></div>`);
        $directory = _this.$wrapper.find('#directory-' + fileSha1);
      }

      $directory.html('');

      new Toc(fileSha1, {
        'level': State.getConfig('directoryMaxDepth'),
        'class': 'toc',
        'top': -1,
        'linkClass': 'mdui-ripple',
        'targetId': 'directory-' + fileSha1
      });

      _this.$wrapper.find('.item').hide();

      if ($directory.html() === '') {
        _this.$wrapper.find('.item.empty').show();
      } else {
        $directory.show();
        $directory.find('a').first().addClass('active');
      }
    });

    /**
     * 监听文章 tab 切换
     */
    Pubsub.subscribe('tab-show', (fileSha1) => {
      if (fileSha1 === 'start' || fileSha1 === 'setting') {
        return;
      }

      let $directory = _this.$wrapper.find('#directory-' + fileSha1);

      _this.$wrapper.find('.item').hide();

      if ($directory.html() === '') {
        _this.$wrapper.find('.item.empty').show();
      } else {
        $directory.show();
      }
    });

    /**
     * 关闭所有文件后
     */
    Pubsub.subscribe('files-all-closed', () => {
      _this.$wrapper.find('.item').each(function() {
        let $this = $$(this);

        if (!$this.hasClass('empty')) {
          $this.remove();
        } else {
          $this.show();
        }
      });
    });

    /**
     * 文章锚点更换后，更新目录状态
     */
    Pubsub.subscribe('article-anchor-change', ({fileSha1, anchor}) => {
      let $directory = _this.$wrapper.find('#directory-' + fileSha1);
      $directory.find('a').removeClass('active');

      // 添加激活状态
      let $active = $directory.find(`[data-id="${anchor}"]`);
      $active.addClass('active');

      // 目录激活的锚点不在可见范围内时，滚动
      let activePositon = $active.position();
      let activeTop = activePositon.top;
      let activeHeight = activePositon.height;
      let wrapperHeight = _this.$wrapper.position().height;

      if (activeTop - 16 < 0) {
        $directory.get(0).scrollTop = $active.get(0).offsetTop - 16;
      } else if (activeTop + activeHeight + 16 > wrapperHeight) {
        $directory.get(0).scrollTop = $active.get(0).offsetTop - wrapperHeight + activeHeight + 16;
      }
    });

    /**
     * 点击目录，跳转文章
     */
    $$(document).on('click', '#sidebar-directory a', function() {
      let $a = $$(this);
      let fileSha1 = $a.parents('.item').attr('id').replace('directory-', '');
      Pubsub.emit('article-to-anchor', {
        fileSha1: fileSha1,
        anchor: $a.data('id')
      });
    });
  }
}

export default SidebarDirectory;